#!/usr/bin/env python
#-*- coding:utf-8 -*-
from flask import render_template, redirect, url_for, request
from . import auth
from forms import LoginForm, RegistrationForm, SetPwdForm
from ..models import User
from .. import db
from flask_login import login_user, logout_user, current_user, login_required


@auth.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(name=form.username.data).first()

        if user is not None and user.verity_password(form.password.data):
            login_user(user)
            # flash(u'登录成功')
            return redirect(url_for('main.index'))
    return render_template('login.html', title=u'登录', form=form)


@auth.route('/logout', methods=['GET', 'POST'])
def logout():
    logout_user()
    return redirect(url_for('auth.login'))


@auth.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        user = User(realname=form.realname.data,
                    name=form.username.data,
                    password=form.password.data)
        db.session.add(user)
        db.session.commit()
        return redirect(url_for('auth.login'))
    return render_template('register.html',
                           title=u'注册',
                           form=form)


@auth.route('/setpwd/<int:id>', methods=['GET', 'POST'])
@login_required
def setpwd(id):
    info = User.query.get_or_404(id)
    form = SetPwdForm()
    if request.method == 'POST' and  info.verity_password(form.oldpassword.data):
        if form.validate_on_submit():
            info.name = form.username.data
            info.realname=form.realname.data
            info.password=form.newpassword.data
            db.session.add(info)
            db.session.commit()
            return redirect(url_for('auth.logout'))
    return render_template('setpwd.html',info=info, form=form)


